package com.zj.java21demo.controller;

import com.zj.java21demo.dto.req.UserAddDto;
import com.zj.java21demo.entity.TUser;
import com.zj.java21demo.mapper.TUserMapper;
import com.zj.java21demo.utils.JwtTokenByJdk21Util;
import com.zj.java21demo.utils.ResultVoUtil;
import com.zj.java21demo.vo.ResultVo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoniuhululu
 * @since 2024-02-22 09:57:01
 */
@RestController
@RequestMapping("/tUser")
@Slf4j
public class TUserController {
    @Resource
    TUserMapper tUserMapper;
    @Resource
    JwtTokenByJdk21Util jwtTokenByJdk21Util;
    @Resource
    PasswordEncoder passwordEncoder;

    @GetMapping("test")
    public ResultVo test() {
        return ResultVoUtil.success("hello world", null);
    }

    @GetMapping("testToken")
    public ResultVo testToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        log.debug(jwtTokenByJdk21Util.extractUsername(token));
        log.debug(jwtTokenByJdk21Util.extractClaim(token, "sex", Integer.class)+"");
        log.debug("end");
        return ResultVoUtil.success("hello world", null);
    }

    @PostMapping("addUser")
    public ResultVo addUser(@RequestBody UserAddDto dto) {
        if(StringUtils.isBlank(dto.getAccount())) {
            return ResultVoUtil.error(400,"账号不允许为空");
        }

        if(StringUtils.isBlank(dto.getPassword())) {
            return ResultVoUtil.error(400,"密码不允许为空");
        }

        TUser user = new TUser();
        user.setAccount(dto.getAccount());
        user.setName(dto.getAccount());
//        user.setPassword(PasswordUtils.encryptPassword(dto.getPassword()));
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setCreateTime(new Date());
        user.setIsActive(1);
        user.setUserStatus(0);
        tUserMapper.insert(user);

        return ResultVoUtil.success("操作成功", null);

    }
}
